<script setup>
import { reactive, ref, computed, onMounted } from "vue";
import { Clock, User } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { removeToken } from "@/composables/cookie";
import { showMessage, showModel } from "@/composables/util.js";
import { updatePassword, updateUserInfo } from "@/api/common/user"
import { uploadFile } from "@/api/common/file"
import { findOrderPageList, changeOrderStatus } from "@/api/common/order"
import moment from 'moment'

// 从浏览器本地存储中取出用户信息
let userInfo = JSON.parse(localStorage.getItem("userInfo"))
const route = useRoute()
const router = useRouter()
// 控制个人信息弹出框
let info = ref(false)
let password = ref(false)
// 设置导航栏激活项
const activeIndex = ref('1')
const form1 = reactive({
  id: null,
  username: null,
  avatar: null,
  token: null
})
const form2 = reactive({
  username: '',
  password: '',
  newPassword: '',
  surePassword: ''
})
onMounted(() => {
    if(userInfo !== null) {
      form1.id = userInfo.id
      form1.username = userInfo.username
      form1.avatar = userInfo.avatar
      form1.token = userInfo.token
      form2.username = userInfo.username
    } 
})

// 修改用户信息
const saveInfo = () => {
    // 调用后端修改用户信息接口
    updateUserInfo(form1).then((res) => {
        if (res.data.success === true) {
            // 提示修改成功
            showMessage('修改成功')
            // 更新存储的用户信息JSON格式到Local Storage(浏览器本地存储) 中
            localStorage.setItem("userInfo", JSON.stringify(res.data.data))
            // 更新之前获取的用户信息变量
            userInfo = JSON.parse(localStorage.getItem("userInfo"))
            info = false
            window.location.reload();
        } else {
            let message = res.data.message
            console.log(message)
            // 提示消息
            showMessage(message, 'error')
        }
    })
}

// 修改用户密码
const savePassword = () => {
    // 调用后端修改用户信息接口
    updatePassword(form2).then((res) => {
        if (res.data.success === true) {
            // 提示修改成功
            showMessage('修改成功')
            // 删除cookie中的token
            removeToken()
            // 删除Local Storage中的userInfo
            localStorage.removeItem('userInfo')
            // 重新跳转登录页面
            router.push('/login')
        } else {
            let message = res.data.message
            console.log(message)
            // 提示消息
            showMessage(message, 'error')
        }
    })

}
// 退出登录方法
const logout = () => {
    showModel('是否退出登录?').then(() => {
        // 删除cookie中的token
        removeToken()
        // 删除Local Storage中的userInfo
        localStorage.removeItem('userInfo')
        showMessage('退出登录成功!')
        // 跳转登录页
        router.push('/login')
    })
}
function goIndex() {
    router.push('/')
}
function goLogin() {
    router.push('/login')
}
function goCollect() {
  router.push('/collect')
}
// 订单状态类型映射
const statusTypeMap = {
    '0': 'primary',
    '1': 'success',
    '2': 'danger'
}

// 当前页码，初值默认为1
const current = ref(1)
// 总记录数，初值默认为0
const total = ref(0)
// 每页显示的记录数，初值默认为10
const size = ref(10)
const orderList = ref([])
// 获取分页数据
function getOrderPageList() {
    console.log("进入getOrderPageList")
    // 调用后台分页接口，并传入所需参数
    findOrderPageList({ current: current.value, size: size.value, userId: userInfo.id })
        .then((res) => {
            if (res.data.success == true) {
                orderList.value = res.data.data
                console.log("订单数据" + JSON.stringify(res.data.data))
                current.value = res.data.current
                size.value = res.data.size
                total.value = res.data.total
            }
        })
}
getOrderPageList()

// 支付
const paySumbit = (id) => {
    showModel('是否购买课程?').then(() => {
        changeOrderStatus({ id: id, status: 1 }).then((res) => {
            if (res.data.success == true) {
                showMessage('购买成功')
                // 重新请求分页接口，渲染数据
                getOrderPageList()
            } else {
                // 获取服务端返回的错误消息
                let message = res.data.message
                // 提示错误消息
                showMessage(message, 'error')
            }
        })
    }).catch(() => {
        console.log('取消了')
    })
}

// 取消订单
const cancelSumbit = (id) => {
    showModel('是否取消订单?').then(() => {
        changeOrderStatus({ id: id, status: 2 }).then((res) => {
            if (res.data.success == true) {
                showMessage('取消成功')
                // 重新请求分页接口，渲染数据
                getOrderPageList()
            } else {
                // 获取服务端返回的错误消息
                let message = res.data.message
                // 提示错误消息
                showMessage(message, 'error')
            }
        })
    }).catch(() => {
        console.log('取消了')
    })
}

const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1 // 重置到第一页
}

</script>

<template>
    <!-- 主容器使用Element布局 -->
    <el-container class="home-container">
        <!-- 导航栏 -->
        <el-header class="header">
            <div class="nav-container">
                <div class="logo">
                    高校<span class="blue">互联网技术</span>在线学习平台
                </div>
                <el-menu mode="horizontal" :default-active="activeIndex">
                    <el-menu-item index="1">
                        <router-link to="/">首页</router-link>
                    </el-menu-item>
                    <el-menu-item index="2">
                        <router-link to="/article-course">图文课程</router-link>
                    </el-menu-item>
                    <el-menu-item index="3">
                        <router-link to="/video-course">视频课程</router-link>
                    </el-menu-item>
                </el-menu>
                <div class="search-box">
                    <el-input placeholder="搜索课程..." suffix-icon="Search" class="search-input" />
                </div>
                <!-- 未登录状态 -->
                <div class="user-wrapper" v-if="!userInfo">
                    <el-button type="primary" class="login-btn" @click="goLogin" round>
                        <i class="el-icon-user"></i>
                        <span>登录 / 注册</span>
                    </el-button>
                </div>

                <!-- 已登录状态 -->
                <div class="user-panel" v-else>
                    <el-dropdown trigger="hover">
                        <div class="user-card">
                            <div class="profile">
                                <el-avatar :src="userInfo.avatar" :size="36" class="user-avatar"
                                    :style="{ backgroundColor: '#8ac8ff' }" />
                            </div>
                        </div>

                        <!-- 下拉菜单 -->
                        <template #dropdown>
                            <el-dropdown-menu class="user-menu">
                                <el-dropdown-item class="menu-item" @click="info = true">
                                    <i class="el-icon-user-solid"></i>个人信息
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item" @click="order = true">
                                    <i class="el-icon-time"></i>我的订单
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item" @click="goCollect">
                                    <i class="el-icon-star-off"></i>我的收藏
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item" @click="password = true">
                                    <i class="el-icon-lock"></i>修改密码
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item logout" @click="logout">
                                    <i class="el-icon-switch-button"></i>退出登录
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </div>
        </el-header>
        <el-main>
            <el-card class="order-list-card">
                <!-- 卡片标题 -->
                <template #header>
                    <div class="card-header">
                        <h3>订单列表</h3>
                    </div>
                </template>

                <!-- 订单行容器 -->
                <div class="order-rows">
                    <!-- 单行订单 -->
                    <div v-for="(order, index) in orderList" :key="index" class="order-row"
                        :class="{ 'active-row': index === activeIndex }">
                        <!-- 左侧内容 -->
                        <div class="row-left">
                            <el-image :src="order.cover" class="row-cover" :preview-src-list="[order.cover]" />
                            <div class="course-info">
                                <div class="title">{{ order.title }}</div>
                                <div class="meta">
                                    <span class="order-id">{{ order.number }}</span>
                                    <el-tag :type="statusTypeMap[order.status]" size="small"
                                        v-if="order.status === 0">待支付</el-tag>
                                    <el-tag :type="statusTypeMap[order.status]" size="small"
                                        v-if="order.status === 1">已支付</el-tag>
                                    
                                </div>
                            </div>
                        </div>

                        <!-- 右侧内容 -->
                        <div class="row-right">
                            <div class="price">{{ order.price }}元</div>
                            <div class="user-time">
                                <div class="user">
                                    <el-icon>
                                        <User />
                                    </el-icon>
                                    {{ order.username }}
                                </div>
                                <div class="time">{{ moment(order.orderTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
                            </div>

                            <!-- 操作按钮组 -->
                            <div class="action-buttons">
                                <el-button v-if="order.status === 0" type="success" size="small"
                                    @click="paySumbit(order.id)">
                                    立即支付
                                </el-button>

                                <el-button v-if="order.status === 0" type="danger" size="small"
                                    @click="cancelSumbit(order.id)">
                                    取消订单
                                </el-button>

                            </div>
                        </div>
                    </div>

                    <!-- 分页底部 -->
                    <div class="demo-pagination-block">
                        <el-pagination v-model:current-page="current" :page-size="[10, 20, 50]" :size="size"
                            :disabled="disabled" background layout="total, prev, pager, next" :total="total"
                            @size-change="handleSizeChange" @current-change="getOrderPageList" />
                    </div>
                </div>

            </el-card>
        </el-main>
    </el-container>

    <!--个人信息对话框-->
    <el-dialog v-model="info" title="个人信息" width="500px" class="custom-dialog">
        <el-form :model="form1" label-width="80px" style="padding: 10px;">
            <el-form-item label="头像">
                <div style="display: flex; align-items: center;">
                    <el-avatar :src="form1.avatar" :icon="UserFilled"
                        style="background-color: #8ac8ff; margin-right: 10px;" />
                    <el-upload :on-change="handleAvatarChange" :auto-upload="false" :show-file-list="false"
                        :file-list="fileList">
                        <el-button size="small" type="primary">修改头像</el-button>
                    </el-upload>
                </div>
            </el-form-item>

            <el-form-item label="用户名">
                <el-input v-model="form1.username" autocomplete="off" placeholder="请输入用户名" style="width: 130px" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer" style="text-align: right;">
                <el-button @click="info = false">取消</el-button>
                <el-button type="primary" @click="saveInfo">保存</el-button>
            </div>
        </template>
    </el-dialog>

    <!--修改密码对话框-->
    <el-dialog v-model="password" title="修改密码" width="500px" class="custom-dialog">
        <el-form :model="form2" label-width="80px" style="padding: 10px;">
            <el-form-item label="旧密码">
                <el-input type="password" v-model="form2.password" autocomplete="off" placeholder="请输入旧密码"
                    style="width: 200px" />
            </el-form-item>
            <el-form-item label="新密码">
                <el-input type="password" v-model="form2.newPassword" autocomplete="off" placeholder="请输入新密码"
                    style="width: 200px" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer" style="text-align: right;">
                <el-button @click="password = false">取消</el-button>
                <el-button type="primary" @click="savePassword">保存</el-button>
            </div>
        </template>
    </el-dialog>

</template>


<style lang="scss" scoped>
$primary-blue: #409EFF;
$hover-blue: rgba(64, 158, 255, 0.1);

.order-list-card {
    max-width: 1200px;
    /* 控制最大宽度 */
    margin: 20px auto;
    /* 水平居中 */
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

    :deep(.el-card__header) {
        background: #f8f9fa;
        border-bottom: 1px solid #ebeef5;
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 20px;

        h3 {
            margin: 0;
            font-size: 18px;
            color: #333;
        }

        .total-info {
            font-size: 14px;
            color: #666;
        }
    }
}

.order-rows {
    padding: 0 15px;
}

.order-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    margin: 8px 0;
    border-radius: 6px;
    border: 1px solid #ebeef5;
    transition: all 0.3s;

    &:hover {
        border-color: #409eff;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
        transform: translateX(5px);
    }

    &.active-row {
        background-color: #f5f7fa;
    }
}

.row-left {
    display: flex;
    align-items: center;
    flex: 1;

    .row-cover {
        width: 80px;
        height: 50px;
        border-radius: 4px;
        margin-right: 15px;
    }

    .course-info {
        .title {
            font-size: 15px;
            color: #333;
            margin-bottom: 6px;
        }

        .meta {
            display: flex;
            align-items: center;
            gap: 10px;

            .order-id {
                font-size: 12px;
                color: #999;
            }
        }
    }
}

.row-right {
    text-align: right;
    min-width: 160px;

    .price {
        font-size: 16px;
        color: #e6a23c;
        font-weight: 500;
        margin-bottom: 8px;
    }

    .user-time {
        font-size: 12px;
        color: #666;

        .user {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 4px;
        }

        .time {
            color: #999;
        }
    }
}

@media (max-width: 768px) {
    .order-list-card {
        margin: 10px;
    }

    .order-row {
        flex-direction: column;
        align-items: stretch;

        .row-right {
            margin-top: 10px;
            text-align: left;
            border-top: 1px dashed #eee;
            padding-top: 10px;
        }
    }
}

.home-container {
    background: #fff;
    min-height: 100vh;

    /* 容器布局 */
    .header {
        height: 70px !important;
        background: #ffffff;
        /* 纯白背景替代毛玻璃 */
        border-bottom: 1px solid #ebeef5;
    }

    .nav-container {
        max-width: 1440px;
        margin: 0 auto;
        display: flex;
        align-items: center;
        height: 100%;
        padding: 0 24px;
    }

    /* Logo样式 */
    .logo {
        font-size: 24px;
        font-weight: 600;
        margin-right: 48px;
        color: #303133;
    }

    .logo .blue {
        color: #409eff;
    }

    /* 导航菜单核心配置 */
    .el-menu--horizontal {
        background: transparent !important;
        border-bottom: none !important;
        flex: 1;
    }

    .el-menu-item {
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        padding: 0 28px;
        color: #606266;
        transition: color 0.3s;
    }

    .el-menu-item.is-active {
        color: #409eff !important;
        border-bottom: 2px solid #409eff;
    }

    /* 搜索框定制 */
    .search-box {
        margin-left: auto;
        margin-right: 24px;
    }

    .search-box .el-input {
        --el-input-border-radius: 20px;
        --el-input-bg-color: #f5f7fa;
    }

    .search-box .el-input__wrapper {
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    }

    /* 用户面板 */
    .user-panel .el-button {
        border-radius: 20px;
        padding: 10px 24px;
        background: #409eff;
        color: white;
    }

    .main-content {
        max-width: 1400px; // 扩大容器宽度
        width: 98%; // 增加自适应能力

        .course-section {
            .el-col {
                @media (min-width: 1200px) {
                    flex: 0 0 25%; // 大屏显示4列课程卡片
                    max-width: 25%;
                }
            }
        }

        margin: 0 auto;
        padding: 20px;



        .category-sidebar {
            .section-title {
                color: #303133;
                font-size: 20px;
                margin-bottom: 15px;
            }

            .category-item {
                display: flex;
                align-items: center;
                padding: 7px;
                transition: all 0.3s;

                &:hover {
                    background: #f8f9fa;
                    transform: translateX(5px);
                }

                .icon-box {
                    width: 40px;
                    height: 40px;
                    border-radius: 8px;
                    margin-right: 15px;
                }

                .cate-name {
                    font-size: 16px;
                    color: #606266;
                }
            }
        }

        // .main-section {
        //   margin-bottom: 40px;
        // }

        // .compact-carousel {

        //   border-radius: 8px;
        //   overflow: hidden;
        //   box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

        //   .carousel-slide {
        //     height: 100%;
        //     display: flex;
        //     align-items: center;
        //     justify-content: center;
        //     background: linear-gradient(135deg, #409EFF, #79bbff);

        //     h2 {
        //       color: white;
        //       font-size: 28px;
        //       text-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
        //     }
        //   }
        // }

        /* 轮播容器优化 */
        .enhanced-carousel {
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        /* 轮播项容器 */
        .carousel-slide {
            position: relative;
            width: 100%;
            height: 100%;
        }

        /* 图片容器 */
        .image-wrapper {
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        /* 图片填充处理 */
        .carousel-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            /* 保持比例填充容器 */
            object-position: center;
            /* 图片中心裁剪 */
            transition: transform 0.3s ease;
        }

        /* 悬浮标题样式 */
        .floating-title {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 20px 30px;
            background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
            color: white;
        }

        .title-text {
            margin: 0;
            font-size: 1.5em;
            text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.5);
        }

        /* 指示器样式优化 */
        :deep(.el-carousel__indicators--outside) {
            bottom: 40px;
            /* 调整指示器位置 */
        }


        /* 悬停效果 */
        @media (hover: hover) {
            .carousel-image:hover {
                transform: scale(1.03);
            }
        }

        .course-section {
            .section-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 30px;
            }

            .course-card {
                transition: all 0.3s;
                margin: 0 10px 15px; // 增加左右间距
                width: calc(100% - 20px); // 防止溢出

                &:hover {
                    transform: translateY(-5px);
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                }

                .course-cover {
                    height: 180px;
                    background: #909399;
                    border-radius: 4px;
                    margin-bottom: 15px;
                }

                .title {
                    color: #303133;
                    font-size: 16px;
                    margin-bottom: 12px;
                }

                .meta {
                    display: flex;
                    justify-content: space-between;
                    color: #909399;

                    .price {
                        color: #F56C6C;
                        font-weight: bold;
                    }
                }
            }
        }
    }
}
</style>
